<?php

namespace app\admin\framework\controller;

use app\admin\framework\api\Permission;
use app\common\model\Nav;

#[Permission('导航管理', 'System')]
class NavController
{

    #[Permission('参数')]
    public function option()
    {
        return apiSuccess(data: [
            'type' => Nav::TYPE
        ]);
    }

    #[Permission('详情')]
    public function detail()
    {
        $id = request()->get('id', 0);
        $result = Nav::find($id)->toArray();
        return apiSuccess(data: $result);
    }

    #[Permission('查询')]
    public function select()
    {
        $data = request()->get();
        $result = Nav::where(function ($query) use ($data) {
            if (!empty($data['keyword'])) {
                $query->where('title', 'like', '%' . $data['keyword'] . '%');
            }
        })->order('list_order asc')->paginate();
        return apiSuccess(data: ['list' => $result->items(), 'total' => $result->total()]);
    }

    #[Permission('创建')]
    public function create()
    {
        if (request()->method() === 'PUT') {
            $data = request()->post();
            if (!empty($data['parent_id'])) {
                $data['type'] = 2;
            }
            (new Nav())->save($data);
            return apiSuccess('保存成功');
        }
        return apiError('保存失败');
    }

    #[Permission('更新')]
    public function update()
    {
        if (request()->method() === 'PUT') {
            $data = request()->post();
            if (!empty($data['parent_id'])) {
                $data['type'] = 2;
            }
            (new Nav())->update($data);
            return apiSuccess('保存成功');
        }
        return apiError('保存失败');
    }


    #[Permission('删除')]
    public function delete()
    {
        if (request()->method() === 'DELETE') {
            $id = request()->get('id', 0);
            if (Nav::destroy($id) !== false) {
                return apiSuccess('删除成功');
            } else {
                return apiError('删除失败');
            }
        }
        return apiError('删除失败');
    }


}